<?php
/**
*
*支付模块
*
*/
class PayAction extends Action{
	public function check(){
		$sname=session('euname');
		if(!isset($sname)) {
			$this->redirect('Member/login');
		}
	}

	public function bank_choose(){
		$Pay=M('Payment');
		$pay=$this->_get('pay');
		$payment=$Pay->where('id='.$pay)->find();
		if($payment['type']=='online'){
			$this->display();
		}else{
		    echo 'offline';
		}		
	}

	//支付准备
	public function ready(){
		$this->check();
		$order_id = $this->_get('order');
		$Order = M('Orders');
		$Payment = M('Payment');
		$map['order_id'] = $order_id;
		$order = $Order->where($map)->find();
		$payment = $Payment->where('id='.$order['payment'])->find();

		if(empty($payment)){
			//exit;
		}
		
		switch($payment['method'])
		{
			case 'tenpay':$pay_url = $this->tenpay($order);break;
			case 'alipay':$pay_url = $this->alipay($order);break;
		    default:$pay_url = '';
		}

		$this->assign("pay_url",$pay_url);
		$this->user = $_SESSION['euname'];
		$this->cat = R('Goods/goods_cat');
		$shop_cart = cookie('shopcart');
		$this->cart_num = !empty($shop_cart)?count(unserialize(stripslashes($shop_cart))):0;
		$this->name = "订单提交成功";
		$this->assign("method",$payment['pay_name']);
		$this->display();
	}

	//财付通支付请求url
	public function tenpay($order)
    {
		vendor('tenpay.classes.RequestHandler','','.class.php');
		//vendor('tenpay.tenpay_config');
		$config=C('TENPAY_CONFIG');

		$spname=$config['spnam'];
		$partner = $config['partner'];
		$key = $config['key'];
		$return_url = $config['return_url'];
		$notify_url = $config['notify_url'];			

		$out_trade_no = $order['order_id'];   //订单号
		$product_name =$order['tostr'];//商品名称
		$order_price = $order['final_money']-$order['payed'];  //获取提交的商品价格
		$remarkexplain = $order['leave_msg'];               //获取提交的备注信息
		/* 支付方式 */
		//$bank_type_value=$order['bank'];    //网银直付

		$strDate = date("Ymd");
		$strTime = date("His");

		/* 商品价格（包含运费），以分为单位 */
		$total_fee = $order_price*100;

		/* 商品名称 */
		$desc =mb_substr($product_name,0,32);
		/* 创建支付请求对象 */
		$reqHandler = new RequestHandler();
		$reqHandler->init();
		$reqHandler->setKey($key);
		$reqHandler->setGateUrl("https://gw.tenpay.com/gateway/pay.htm");

		//----------------------------------------
		//设置支付参数 
		//----------------------------------------
		$reqHandler->setParameter("partner", $partner);
		$reqHandler->setParameter("out_trade_no", $out_trade_no);
		$reqHandler->setParameter("total_fee", $total_fee);  //总金额
		$reqHandler->setParameter("return_url", $return_url);
		$reqHandler->setParameter("notify_url", $notify_url);
		$reqHandler->setParameter("body", $desc);
		$reqHandler->setParameter("bank_type", $bank_type_value); 
		//用户ip
		$reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']);//客户端IP
		$reqHandler->setParameter("fee_type", "1");               //币种
		$reqHandler->setParameter("subject",$desc);          //商品名称，（中介交易时必填）

		//系统可选参数
		$reqHandler->setParameter("sign_type", "MD5");  	 	  //签名方式，默认为MD5，可选RSA
		$reqHandler->setParameter("service_version", "1.0"); 	  //接口版本号
		$reqHandler->setParameter("input_charset", "utf-8");   	  //字符集
		$reqHandler->setParameter("sign_key_index", "1");    	  //密钥序号

		//业务可选参数
		$reqHandler->setParameter("attach", "");             	  //附件数据，原样返回就可以了
		$reqHandler->setParameter("product_fee", "");        	  //商品费用
		$reqHandler->setParameter("transport_fee", "0");      	  //物流费用
		$reqHandler->setParameter("time_start", date("YmdHis"));  //订单生成时间
		$reqHandler->setParameter("time_expire", "");             //订单失效时间
		$reqHandler->setParameter("buyer_id", "");                //买方财付通帐号
		$reqHandler->setParameter("goods_tag", "");               //商品标记
		$reqHandler->setParameter("trade_mode","1");              //交易模式1.即时到帐模式2.中介担保模式
		$reqHandler->setParameter("transport_desc","");              //物流说明
		$reqHandler->setParameter("trans_type","1");              //交易类型
		$reqHandler->setParameter("agentid","");                  //平台ID
		$reqHandler->setParameter("agent_type","");               //代理模式（0.无代理，1.表示卡易售模式，2.表示网店模式
		$reqHandler->setParameter("seller_id","");                //卖家的商户号

		//请求的URL
		$reqUrl = $reqHandler->getRequestURL();

		//获取debug信息,建议把请求和debug信息写入日志，方便定位问题
		/**/
		$debugInfo = $reqHandler->getDebugInfo();
		return $reqUrl;
	}

	//支付回调页面:用户
	public function tenpay_result(){
		$this->check();
		vendor('tenpay.classes.ResponseHandler','','.class.php');
		vendor('tenpay.classes.RequestHandler','','.class.php');
		vendor('tenpay.classes.client.ClientResponseHandler','','.class.php');
		vendor('tenpay.classes.client.TenpayHttpClient','','.class.php');

		$config=C('TENPAY_CONFIG');

		$spname=$config['spnam'];
		$partner = $config['partner'];
		$key = $config['key'];
		$return_url = $config['return_url'];
		$notify_url = $config['notify_url'];


	    /* 创建支付应答对象 */
		$resHandler = new ResponseHandler();
		$resHandler->setKey($key);

	    //判断签名
	    //$res=$resHandler->isTenpaySign();
		//if($resHandler->isTenpaySign()) {
			//$this->redirect("pay_error");
		//}
	
		$notify_id = $resHandler->getParameter("notify_id");
		$queryReq = new RequestHandler();
		$queryReq->init();
		$queryReq->setKey($key);
		$queryReq->setGateUrl("https://gw.tenpay.com/gateway/simpleverifynotifyid.xml");
		$queryReq->setParameter("partner", $partner);
		$queryReq->setParameter("notify_id", $notify_id);
		
		//通信对象
		$httpClient = new TenpayHttpClient();
		$httpClient->setTimeOut(5);
		//设置请求内容
		$httpClient->setReqContent($queryReq->getRequestURL());
	
		//后台调用
		if($httpClient->call()) {
			//设置结果参数
			$queryRes = new ClientResponseHandler();
			$queryRes->setContent($httpClient->getResContent());
			$queryRes->setKey($key);
		
			if($resHandler->getParameter("trade_mode") == "1"){
				//判断签名及结果（即时到帐）
				//只有签名正确,retcode为0，trade_state为0才是支付成功
				if($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" && $resHandler->getParameter("trade_state") == "0") {

					
					$out_trade_no = $resHandler->getParameter("out_trade_no");//取结果参数做业务处理
					$transaction_id = $resHandler->getParameter("transaction_id");//财付通订单号
					$total_fee = $resHandler->getParameter("total_fee");//金额,以分为单位
					$discount = $resHandler->getParameter("discount");//如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee

					//处理业务开始
					$result=array("retcode"=>$queryRes->getParameter("retcode"),
										  "trade_state"=>$queryRes->getParameter("retcode"),
					                      "order_id"=>$out_trade_no,
					                      "payid"=>$transaction_id,
					                      "payed"=>$total_fee,
					                 );

					 $this->assign("payres",$result);

					 $this->user=$_SESSION['euname'];
					 $this->cat=R('Goods/goods_cat');
					 $shop_cart=cookie('shopcart');
					 $this->cart_num=!empty($shop_cart)?count(unserialize(stripslashes($shop_cart))):0;
				     $this->name="支付结果";
					 $this->tel=C('KEFU_TEL');
					 $this->display();
				}else{
						$this->redirect("pay_error");
				}
			}else{
				$this->redirect('Member/index');
	        }
		}
	}

	//支付处理页面：后台处理
	public function tenpay_do_result(){
		vendor('tenpay.classes.ResponseHandler','','.class.php');
		$config=C('TENPAY_CONFIG');

		$spname=$config['spnam'];
		$partner = $config['partner'];
		$key = $config['key'];
		$return_url = $config['return_url'];
		$notify_url = $config['notify_url'];

		$resHandler = new ResponseHandler();
		$resHandler->setKey($key);

		//判断签名
		//if($resHandler->isTenpaySign()) {
			$notify_id = $resHandler->getParameter("notify_id");//通知id
			$out_trade_no = $resHandler->getParameter("out_trade_no");//商户订单号
			$transaction_id = $resHandler->getParameter("transaction_id");//财付通订单号
			$total_fee = $resHandler->getParameter("total_fee");
			$discount = $resHandler->getParameter("discount");
			$trade_state = $resHandler->getParameter("trade_state");
			$trade_mode = $resHandler->getParameter("trade_mode");
			
			if($trade_state=='0'){
				$order_id=$out_trade_no;
				$payed=$total_fee/100.0;
				$time=time();

				$Order=M('Orders');
				$Log=M('Order_log');
				$Pay=M('Order_pay');
				$ck['order_id']=$order_id;
				$ck['payed']=$payed;
				$ck['trade_no']=$transaction_id;

				$ckor['order_id']=$order_id;
				$order=$Order->where($ckor)->find();

				if($Pay->where($ck)->select()){
					exit;
				}else{
					$order['payed']=$payed;
					$order['pay_status']=1;
					$order['last_time']=$time;

					$log['order_id']=$order_id;
					$log['op_name']=$_SESSION['euname'];
					$log['log_text']="订单：".$order_id."网银付款:{$order['payed']}";
					$log['acttime']=$time;
					$log['behavior']="订单付款";
					$log['result']="success";

					$pay['order_id']=$order_id;
					$pay['payed']=$payed;
					$pay['payment']=$order['payment'];
					$pay['pay_time']=$time;
					$pay['trade_no']=$transaction_id;
					$pay['result']="success";

					$result=$Order->where('order_id='.$order_id)->save($order);
					$Log->add($log);
					$pay_re=$Pay->add($pay);
					if(C('SMS_OPEN')==1){
						R('Public/send_sms',array($_SESSION['euname'],$order_id));
					}
				}

			}else{
				$this->error("付款失败！");
			}
		//}
	}

	//支付宝支付url
	public function alipay($order)
	{
		vendor('alipay.alipay_core','','.function.php');
		vendor('alipay.alipay_md5','','.function.php');
		vendor('alipay.alipay_notify','','.class.php');
		vendor('alipay.alipay_submit','','.class.php');
		$alipay_config = C('ALIPAY_CONFIG');

        $payment_type = "1";
        $notify_url        = $alipay_config['notify_url'];//服务器异步通知页面路径
        $return_url       = $alipay_config['return_url'];//页面跳转同步通知页面路径
        $seller_email   = $alipay_config['alipay_account'];//卖家支付宝帐户
        $out_trade_no = $order['order_id'];//商户订单号
        $subject           = $order['tostr'];//订单名称
        $total_fee        = $order['final_money']-$order['payed'];//付款金额
        $body              = $order['tostr'];//订单描述
        $show_url        = "";
        $anti_phishing_key = ""; //防钓鱼时间
        $exter_invoke_ip = $order['user_ip']; //客户端的IP地址

		//构造要请求的参数数组，无需改动
		$parameter = array(
				"service" => "create_direct_pay_by_user",
				"partner" => trim($alipay_config['partner']),
				"payment_type"	=> $payment_type,
				"notify_url"	=> $notify_url,
				"return_url"	=> $return_url,
				"seller_email"	=> $seller_email,
				"out_trade_no"	=> $out_trade_no,
				"subject"	=> $subject,
				"total_fee"	=> $total_fee,
				"body"	=> $body,
				"show_url"	=> $show_url,
				"anti_phishing_key"	=> $anti_phishing_key,
				"exter_invoke_ip"	=> $exter_invoke_ip,
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
		);

		//建立请求
		$alipaySubmit = new AlipaySubmit($alipay_config);
		$html_text = $alipaySubmit->buildRequestParaToString($parameter);
		return $html_text;
	}

	public function alipay_result()
	{
		vendor('alipay.alipay_core','','.function.php');
		vendor('alipay.alipay_md5','','.function.php');
		vendor('alipay.alipay_notify','','.class.php');
		$alipay_config = C('ALIPAY_CONFIG');

		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyReturn();

		if($verify_result) {
			$out_trade_no = $_GET['out_trade_no'];
			$trade_no = $_GET['trade_no'];//支付宝交易号
			$trade_status = $_GET['trade_status'];//交易状态

			if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
				$result=array(
										  "trade_state"=>0,
					                      "order_id"=>$out_trade_no,
					                      "payid"=>$trade_no,
					                 );
				 $this->assign("payres",$result);
				 $this->user=$_SESSION['euname'];
				 $this->cat=R('Goods/goods_cat');
				 $shop_cart=cookie('shopcart');
				 $this->cart_num=!empty($shop_cart)?count(unserialize(stripslashes($shop_cart))):0;
				 $this->name="支付结果";
				 $this->tel=C('KEFU_TEL');
				 $this->display();
			}
		}else{
			$this->error("支付失败，请重试");
		}
	}

	public function alipay_do_result()
	{
		vendor('alipay.alipay_core','','.function.php');
		vendor('alipay.alipay_md5','','.function.php');
		vendor('alipay.alipay_notify','','.class.php');
		$alipay_config = C('ALIPAY_CONFIG');
		
		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if(!$verify_result) {
			echo "fail";
			//exit;
		}
		$out_trade_no = $_POST['out_trade_no'];
		$trade_no = $_POST['trade_no'];
		$trade_status = $_POST['trade_status'];

		if(($_POST['trade_status'] != 'TRADE_FINISHED') && ($_POST['trade_status'] != 'TRADE_SUCCESS'))
		{
			echo "fail";
		}
		//业务处理
		$order_id=$out_trade_no;
		$time=time();

		$Order =M('Orders');
		$ckor['order_id']=$order_id;
		$order = $Order->where($ckor)->find();

		$PayModel = new PayModel();
		$ck['order_id']  = $order_id;
		$ck['trade_no'] = $trade_no;
		$is_pay = $PayModel->getPayDetail($ck);

		if(!empty($is_pay)) {
			echo "fail";
			//exit;
		}

		$up_order['payed'] = $order['final_money']-$order['payed'];
		$up_order['pay_status']=1;
		$up_order['last_time']=$time;
		$result = $Order->where($ckor)->save($up_order);

		if($result){
			$Log =M('Order_log');
			$log['order_id']=$order_id;
			$log['op_name']=session('euname');
			$log['log_text']="订单：".$order_id."支付宝付款:{$up_order['payed']}";
			$log['acttime']=$time;
			$log['behavior']="订单付款";
			$log['result']="success";
			$Log->add($log);

			$pay_info['order_id']  = $order_id;
			$pay_info['payed']      = $up_order['payed'];
			$pay_info['payment']   = $order['payment'];
			$pay_info['pay_time']  =$time;
			$pay_info['trade_no']   = $trade_no;
			$pay_info['result']        = "success";
			$res = $PayModel->addPay($pay_info);
		}

		if(C('SMS_OPEN')==1){
			R('Public/send_sms',array($_SESSION['euname'],$order_id));
		}

		echo "success";
	}


	//支付方式
	public function payment(){
		$Pay=M('Payment');
		$map['is_use']=1;
		$res = $Pay->where($map)->order("id")->select();
		return $res;
	}


}